package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_CODE_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendcode(String phone, HttpSession session) {
        //手机号格式验证
        if (RegexUtils.isPhoneInvalid(phone)){
            log.info("手机格式错误");
            return Result.fail("手机格式错误");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        //验证码存进redis
        stringRedisTemplate.opsForValue()
                .set(LOGIN_CODE_KEY+phone,code,30, TimeUnit.MINUTES);
        //发送验证码
        log.info("验证码：{}",code);
        return Result.ok();
    }

    /**
     * 用户登录——将user信息存入session
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        //手机号格式验证
        if (RegexUtils.isPhoneInvalid(phone)){
            log.info("手机格式错误");
            return Result.fail("手机格式错误");
        }
        //判断code是否对齐
        String cacheCode = stringRedisTemplate.opsForValue()
                .get(LOGIN_CODE_KEY + phone);
        if (cacheCode == null) return Result.fail("手机号不正确");
        if (!cacheCode.equals(code)) {
            return Result.fail("验证码错误");
        }
        //查询用户存在
        User user = query().eq("phone", phone).one();
        //不存在：创建用户->创建token,将token与user作为键值对存进redis
        if (user == null){
            //创建userWhileNull
            User userWhileNull = new User();
            userWhileNull.setNickName("user"+RandomUtil.randomString(6));
            userWhileNull.setPhone(phone);
            userWhileNull.setUpdateTime(LocalDateTime.now());
            userWhileNull.setCreateTime(LocalDateTime.now());
            save(userWhileNull);
            //创建UserDTO
            UserDTO userDTOWhileNull = new UserDTO();
            BeanUtils.copyProperties(userWhileNull, userDTOWhileNull);

            //存入redis
            Map<String, Object> userMapWN = BeanUtil.beanToMap(
                    userDTOWhileNull,new HashMap<>(),
                    CopyOptions.create().setIgnoreNullValue(true)
                            .setFieldValueEditor((fileName,fileValue)->fileValue.toString()));
            UUID token = UUID.randomUUID();
            stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,userMapWN);
            stringRedisTemplate.expire(LOGIN_USER_KEY+token,30,TimeUnit.MINUTES);
            return Result.ok(token);
        }
        //判断redis是否存在user这个对象
        else {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user,userDTO);
            UUID token = UUID.randomUUID();
            Map<String, Object> userMap = BeanUtil.beanToMap(
                    userDTO,new HashMap<>(),
                    CopyOptions.create().setIgnoreNullValue(true)
                            .setFieldValueEditor((fileName,fileValue)->fileValue.toString()));
            stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,userMap);
            stringRedisTemplate.expire(LOGIN_USER_KEY+token,30,TimeUnit.MINUTES);
            return Result.ok(token);
        }

    }

}
